package com.yonyou.ucf.mdf.app.isvdxq.firstpart.location.service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.yonyou.ucf.mdf.app.isvdxq.common.ApiYon;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.location.entity.OrderStoreDetailEntity;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.location.entity.OrderStoreEntity;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.location.mapper.OrderStoreDetailMapperImpl;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.location.mapper.OrderStoreMapperImpl;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.location.model.*;
import com.yonyou.ucf.mdf.app.isvdxq.utils.GenericResponse;
import com.yonyou.ucf.mdf.app.isvdxq.utils.RequestTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class OrderStoreService {
    @Autowired
    private OrderStoreMapperImpl orderStoreMapper;
    @Autowired
    private OrderStoreDetailMapperImpl orderStoreDetailMapper;



    public OrderStoreEntity selectById(Integer id) {
        return orderStoreMapper.selectByPrimaryKey(id);
    }

    public OrderStoreEntity selectByMainId(String id) {
        return orderStoreMapper.selectByMainId(id);
    }

    public Boolean CheckEntity(String Id) {
        int rInt = orderStoreMapper.selectCount(Id);
        if (rInt > 0) return true;
        else return false;
    }

    public int EditEntityFlag(String Id) {
        return orderStoreMapper.editEntityFlag(Id);
    }

    /**
     * 返回自增Id
     *
     * @param entity
     * @return
     */
    public int InsertEntity(OrderStoreEntity entity) {
        return orderStoreMapper.insert(entity);
    }

    public int insertSelective(OrderStoreEntity record) {
        return orderStoreMapper.insertSelective(record);
    }

    public int updateByPrimaryKeySelective(OrderStoreEntity record) {
        return orderStoreMapper.updateByPrimaryKeySelective(record);
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean AutoDataInByOrderId(String token, String orderId, String operateuserid, String gatewayUrl, List<OrderStoreAddBean> dataList) throws IOException {
        boolean res = false;
        Map<String, String> params = new HashMap<>();
        // 除签名外的其他参数
        params.put("id", orderId);
        params.put("access_token", token);
        // 请求
        String requestUrl = gatewayUrl + ApiYon.getPurinDetail;
        String resString = RequestTool.doGet(requestUrl, params);
        GenericResponse<OrderStoreInAPI> response = RequestTool.getBean(resString, new TypeReference<GenericResponse<OrderStoreInAPI>>() {
        });

        if (response.getCode().equals("200")) {
            OrderStoreInAPI orderStoreInAPI = response.getData();
            List<OrderStoreInAPIDetail> details = orderStoreInAPI.getPurInRecords();
            if (orderStoreInAPI.getId() > 0 && details.size() > 0) {
                String mainId = String.valueOf(orderStoreInAPI.getId());
                boolean flagNext = CheckEntity(mainId);
                if (flagNext) {
                    int rIntFlag1 = EditEntityFlag(mainId);
                    int rIntFlag2 = orderStoreDetailMapper.editEntityFlagByMainId(mainId);
                }

                //写入主表
                OrderStoreEntity orderStoreEntity = new OrderStoreEntity();
                orderStoreEntity.setType(2);//1入 2出
                orderStoreEntity.setDatatype(0);//无标签库存
                orderStoreEntity.setCode(orderStoreInAPI.getCode());
                orderStoreEntity.setMainid(String.valueOf(orderStoreInAPI.getId()));
                orderStoreEntity.setStatus(orderStoreInAPI.getStatus());
                orderStoreEntity.setTranstype(orderStoreInAPI.getBustype());
                orderStoreEntity.setWarehouseid(String.valueOf(orderStoreInAPI.getWarehouse()));
                orderStoreEntity.setInventoryowner(String.valueOf(orderStoreInAPI.getInventoryowner()));
                orderStoreEntity.setShopid(String.valueOf(orderStoreInAPI.getShop()));
                orderStoreEntity.setTplid(String.valueOf(orderStoreInAPI.getTplid()));
                String sourceId = String.valueOf(orderStoreInAPI.getPurInRecords().get(0).getSourceid());
                String sourceCode = orderStoreInAPI.getPurInRecords().get(0).getSource();
                orderStoreEntity.setSourcecode(sourceCode);
                orderStoreEntity.setSourceid(sourceId);
                String firstsourceId = String.valueOf(orderStoreInAPI.getPurInRecords().get(0).getFirstsourceid());
                String firstsourceCode = orderStoreInAPI.getPurInRecords().get(0).getFirstsource();
                orderStoreEntity.setFirstsourcecode(firstsourceCode);
                orderStoreEntity.setFirstsourceid(firstsourceId);
                orderStoreEntity.setOperatetime(orderStoreInAPI.getPubts());
                orderStoreEntity.setOperateuserid(operateuserid);

                int rInt = orderStoreMapper.insert(orderStoreEntity);
                System.out.println(rInt);

                //批量写入详情
                List<OrderStoreDetailEntity> list = new ArrayList<>();
                String storeId = String.valueOf(rInt);
                List<OrderStoreInAPIDetail> detailList = details;
                if (dataList != null) {
                    List<Long> detailids = dataList.stream().map(it -> Long.parseLong(it.getId())).distinct().collect(Collectors.toList());
                    detailList = details.stream().filter(it -> detailids.contains(it.getId())).collect(Collectors.toList());
                }
                detailList.forEach(item -> {
                    OrderStoreDetailEntity obj = new OrderStoreDetailEntity();
                    obj.setStoreid(storeId);
                    obj.setMainid(orderStoreEntity.getMainid());
                    obj.setDetailid(String.valueOf(item.getId()));
                    obj.setInventoryowner(orderStoreEntity.getInventoryowner());
                    obj.setReserveid(orderStoreEntity.getReceiveid());
                    obj.setTplid(orderStoreEntity.getTplid());
                    obj.setOrderid(String.valueOf(item.getPoid()));
                    obj.setOrderdetailid(String.valueOf(item.getPodetailid()));
                    obj.setSourceid(String.valueOf(item.getSourceid()));
                    obj.setSourceautoid(String.valueOf(item.getSourceautoid()));
                    obj.setSourcecode(item.getSource());
                    obj.setFirstsourceid(String.valueOf(item.getFirstsourceid()));
                    obj.setFirstsourceautoid(String.valueOf(item.getFirstsourceautoid()));
                    obj.setFirstsourcecode(item.getFirstsource());
                    obj.setUnitid(String.valueOf(item.getUnit()));
                    obj.setStockunitid(String.valueOf(item.getStockUnitId()));
                    obj.setProductid(String.valueOf(item.getProduct()));
                    obj.setProductskuid(String.valueOf(item.getProductsku()));
                    obj.setWarehouseid(String.valueOf(orderStoreEntity.getWarehouseid()));
                    obj.setStorecount(item.getQty());
                    obj.setEpccount(item.getSubQty());
                    obj.setOperatetime(item.getPubts());
                    obj.setOperateuserid(orderStoreEntity.getOperateuserid());
                    list.add(obj);
                });

                int rInt2 = orderStoreDetailMapper.insertBatch(list);

                res = true;
            }
        }
        return res;
    }


    @Transactional(rollbackFor = Exception.class)
    public boolean AutoDataOutByOrderId(String token, String orderId, String operateuserid, String gatewayUrl, List<OrderStoreAddBean> dataList) throws IOException {
        boolean res = false;
        Map<String, String> params = new HashMap<>();
        // 除签名外的其他参数
        params.put("id", orderId);
        params.put("access_token", token);
        // 请求
        String requestUrl = gatewayUrl + ApiYon.getSalesoutDetail;
        String resString = RequestTool.doGet(requestUrl, params);
        GenericResponse<OrderStoreOutAPI> response = RequestTool.getBean(resString, new TypeReference<GenericResponse<OrderStoreOutAPI>>() {
        });

        if (response.getCode().equals("200")) {
            OrderStoreOutAPI orderStoreOutAPI = response.getData();
            List<OrderStoreOutAPIDetail> details = orderStoreOutAPI.getDetails();
            if (orderStoreOutAPI.getId() > 0 && details.size() > 0) {
                String mainId = String.valueOf(orderStoreOutAPI.getId());
                boolean flagNext = CheckEntity(mainId);
                if (flagNext) {
                    int rIntFlag1 = EditEntityFlag(mainId);
                    int rIntFlag2 = orderStoreDetailMapper.editEntityFlagByMainId(mainId);
                }

                //写入主表
                OrderStoreEntity orderStoreEntity = new OrderStoreEntity();
                orderStoreEntity.setType(2);//1入 2出
                orderStoreEntity.setDatatype(0);//无标签库存
                orderStoreEntity.setCode(orderStoreOutAPI.getCode());
                orderStoreEntity.setMainid(String.valueOf(orderStoreOutAPI.getId()));
                orderStoreEntity.setStatus(orderStoreOutAPI.getStatus());
                orderStoreEntity.setTranstype(orderStoreOutAPI.getBustype());
                orderStoreEntity.setWarehouseid(String.valueOf(orderStoreOutAPI.getWarehouse()));
                orderStoreEntity.setInventoryowner(String.valueOf(orderStoreOutAPI.getInventoryowner()));
                orderStoreEntity.setShopid(String.valueOf(orderStoreOutAPI.getShop()));
                orderStoreEntity.setReceiveid(String.valueOf(orderStoreOutAPI.getReceiveId()));
                String sourceId = String.valueOf(orderStoreOutAPI.getDetails().get(0).getSourceid());
                String sourceCode = orderStoreOutAPI.getDetails().get(0).getSource();
                orderStoreEntity.setSourcecode(sourceCode);
                orderStoreEntity.setSourceid(sourceId);
                String firstsourceId = String.valueOf(orderStoreOutAPI.getDetails().get(0).getFirstsourceid());
                String firstsourceCode = orderStoreOutAPI.getDetails().get(0).getFirstsource();
                orderStoreEntity.setFirstsourcecode(firstsourceCode);
                orderStoreEntity.setFirstsourceid(firstsourceId);
                orderStoreEntity.setOperatetime(orderStoreOutAPI.getPubts());
                orderStoreEntity.setOperateuserid(operateuserid);

                int rInt = orderStoreMapper.insert(orderStoreEntity);

                //批量写入详情
                List<OrderStoreDetailEntity> list = new ArrayList<>();
                String storeId = String.valueOf(rInt);
                List<OrderStoreOutAPIDetail> detailList = details;
                if (dataList != null) {
                    List<Long> detailids = dataList.stream().map(it -> Long.parseLong(it.getId())).distinct().collect(Collectors.toList());
                    detailList = details.stream().filter(it -> detailids.contains(it.getId())).collect(Collectors.toList());
                }
                detailList.forEach(item -> {
                    OrderStoreDetailEntity obj = new OrderStoreDetailEntity();
                    obj.setStoreid(storeId);
                    obj.setMainid(orderStoreEntity.getMainid());
                    obj.setDetailid(String.valueOf(item.getId()));
                    obj.setInventoryowner(orderStoreEntity.getInventoryowner());
                    obj.setReserveid(orderStoreEntity.getReceiveid());
                    obj.setTplid(orderStoreEntity.getTplid());
                    obj.setOrderid(String.valueOf(item.getOrderId()));
                    obj.setOrderdetailid(String.valueOf(item.getOrderDetailId()));
                    obj.setSourceid(String.valueOf(item.getSourceid()));
                    obj.setSourceautoid(String.valueOf(item.getSourceautoid()));
                    obj.setSourcecode(item.getSource());
                    obj.setFirstsourceid(String.valueOf(item.getFirstsourceid()));
                    obj.setFirstsourceautoid(String.valueOf(item.getFirstsourceautoid()));
                    obj.setFirstsourcecode(item.getFirstsource());
                    obj.setUnitid(String.valueOf(item.getUnit()));
                    obj.setStockunitid(String.valueOf(item.getStockUnitId()));
                    obj.setProductid(String.valueOf(item.getProduct()));
                    obj.setProductskuid(String.valueOf(item.getProductsku()));
                    obj.setWarehouseid(String.valueOf(orderStoreEntity.getWarehouseid()));
                    obj.setStorecount(item.getQty());
                    obj.setEpccount(item.getSubQty());
                    obj.setOperatetime(item.getPubts());
                    obj.setOperateuserid(orderStoreEntity.getOperateuserid());
                    list.add(obj);
                });

                int rInt2 = orderStoreDetailMapper.insertBatch(list);

                res = true;
            }
        }
        return res;
    }
}
